import { Alert, Button, Col, Form, Input, InputNumber, message, Radio, Row, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import ActionSet from '../../../components/ActionSet';
import FormItem from '../../../components/FormItem';
import ScriptEditor from '../../../components/ScriptEditor';
import useVariableData from '../../../hook/useVariableData';
import services from '../../../services/api';
import { compare, compareClass } from '../../../utils/compare';
import { CALC_TYPE, IS_SYSTEM, NEED_CALC, VARIABLE_TYPE } from '../../../utils/constant';
import useAppProductEventData from 'src/hook/useAppProductEventData';
import { connect } from 'react-redux';
import DataTypeDesc from '../../../components/DataTypeDesc'

function FieldAdd(props) {
  const {
    is_system,
    field_name,
    field_code,
    data_type,
    max_length,
    need_calc,
    calc_type,
    remark,
    classification,
    // need_encrypt,
  } = props.value || {};

  const [actionList, setActionList] = useState([]); // 函数列表
  const [value, setValue] = useState({}); // 函数列表
  const [using_variables, setUsingVariables] = useState([]);

  // const [dataSourceType, setDataSourceType] = useState('1');
  const [calcContent, setCalcContent] = useState({}); //计算内容
  const [calcContentText, setCalcContentText] = useState(''); //groveey

  const [fieldId, setFieldId] = useState('');

  const { items, appId, eventId } = useAppProductEventData({
    ...props,
    app_id: value.app_id,
    event_id: value.event_id,
    event_name: value.event_name,
    product_id: value.product_id,
    disabled: props.actionType !== 'add' && props.actionType !== 'copy',
    form: props.form,
    layout: {
      className: 'tantuer-form-item3 tantuer-form-item-nowrap',
    },
  });

  const variable = useVariableData({
    limitType: [
      VARIABLE_TYPE._FIELD,
      VARIABLE_TYPE._FEATURE,
      VARIABLE_TYPE._MODEL,
      VARIABLE_TYPE._NAMELIST,
      VARIABLE_TYPE._THIRD_FEATURE,
      VARIABLE_TYPE._STRATEGY,
      VARIABLE_TYPE._RISK_LEVEL,
      VARIABLE_TYPE._LITERAL,
    ],
    appId,
    eventId,
  }); //字段添加页，默认需要字段、指标的变量

  useEffect(() => {
    getActions(); //获取函数列表
    if ((props.actionType === 'update' || props.actionType === 'detail') && props.record && props.record.field_id && !props.isAuditLog) {
      getDetail(); // 获取详情
    }
    // if (props.value && Object.keys(props.value).length > 0) {
    //   setDetail(props.value);
    // }
  }, []);
  useEffect(() => {
    if (props.value && Object.keys(props.value).length > 0) {
      setDetail(props.value, true);
    }
  }, [props.value]);

  // 获取函数列表
  function getActions() {
    services.action.actionList({ usage_scope_limit: 'field' }).then((res) => {
      if (res.code === 0) {
        setActionList(res.data);
      }
    });
  }

  /**获取详情 */
  function getDetail() {
    services.field.queryOne({ field_id: props.record.field_id }).then((res) => {
      if (res.code === 0) {
        setDetail(res.data, true);
      } else {
        message.error(res.msg);
      }
    });
  }

  function setDetail(data, isSetFormValue) {
    setUsingVariables(data.using_variables);
    if (isSetFormValue) {
      props.form.setFieldsValue({
        app_id: data.app_id,
        data_type: data.data_type,
        product_id: data.product_id || '',
        event_id: data.event_id,
        field_code: data.field_code,
        field_name: data.field_name,
        is_system: data.is_system,
        max_length: data.max_length,
        name: data.name,
        need_calc: data.need_calc,
        remark: data.remark,
      });
      setTimeout(() => {
        props.form.setFieldsValue({
          calc_type: data.calc_type,
        });
      }, 200);
    }
    setValue(data);
    setFieldId(data.field_id);
    if (data.calc_type === CALC_TYPE._CONFIG) {
      setCalcContent(data.calc_content);
    }
    if (data.calc_type === CALC_TYPE._SQ) {
      setCalcContentText(data.calc_content);
    }
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        let params = {};
        if (values.is_system === IS_SYSTEM._TRUE) {
          params = {
            ...values,
          };
        } else if (values.is_system === IS_SYSTEM._FALSE) {
          params = {
            ...values,
          };
          if (values.need_calc === NEED_CALC._TRUE && values.calc_type === CALC_TYPE._CONFIG) {
            if (Object.keys(calcContent).length === 0) {
              message.warning('请编辑函数');
              return;
            } else {
              params.calc_content = calcContent;
            }
          }
          if (values.need_calc === NEED_CALC._TRUE && values.calc_type === CALC_TYPE._SQ) {
            if (calcContentText === '') {
              message.warning('请编辑JavaScript脚本');
              return;
            } else {
              params.calc_content = calcContentText;
            }
          }
        }
        if (props.actionType === 'add') {
          const txt = props.form.getFieldValue('is_system') === IS_SYSTEM._FALSE ? 'ext_' : 'sys_';
          params.field_code = txt + values.field_code;
        }
        if (props.actionType === 'update') {
          params.field_id = fieldId;
        }
        services.field[props.actionType](params).then((data) => {
          if (data.code === 0) {
            message.success(data.msg);
            if (props.closeModal) {
              props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  const handleChangeAction = (value) => {
    setCalcContent(value);
  };

  const handleScript = (value) => {
    setCalcContentText(value);
  };

  const handleTypeChange = () => {
    props.form.setFieldsValue({
      max_length: 64
    })
  }

  const formItems = [
    {
      label: {
        label: '字段类型',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        help:
          props.form.getFieldValue('is_system') === IS_SYSTEM._TRUE
            ? '系统字段无需选择关联事件，默认可在各事件使用'
            : '',
      },
      name: 'is_system',
      options: {
        initialValue: is_system || IS_SYSTEM._FALSE || 0,
        rules: [{ required: true, message: '请输入时间范围' }],
      },
      component: (
        <Radio.Group disabled={props.actionType !== 'add'} className={compareClass(props, 'is_system')}>
          <Radio.Button value={IS_SYSTEM._TRUE}>系统字段</Radio.Button>
          <Radio.Button value={IS_SYSTEM._FALSE}>自定义字段</Radio.Button>
        </Radio.Group>
      ),
    },
    {
      label: {
        label: '字段分类',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'classification',
      options: {
        initialValue: classification,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select
          style={{ width: '100%', ...compare(props, 'classification') }}
          placeholder='请选择'
          disabled={props.actionType !== 'add'}
        >
          {props.field_classification.map((it) => {
            return (
              <Select.Option value={it.code} key={it.code}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
    }
  ];
  const formItems2 = [
    ...items.map((it) => (props.form.getFieldValue('is_system') === IS_SYSTEM._FALSE && !props.isImport ? it : false)),
    {
      label: {
        label: '字段名',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'field_name',
      options: {
        initialValue: field_name,
        rules: [
          { required: true, message: '请填写' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
        ],
      },
      component: (
        <Input placeholder='请填写' disabled={props.actionType === 'detail'} style={compare(props, 'field_name')} />
      ),
    },
    {
      label: {
        label: '字段Code',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        extra: '字段Code开始接入时使用，创建后不可修改',
      },
      name: 'field_code',
      options: {
        initialValue: field_code,
        rules: [
          { required: true, message: '请填写' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[_a-zA-Z0-9]+$/, message: '限英文数字下划线' },
        ],
      },
      component: (
        <Input
          addonBefore={
            props.actionType !== 'add'
              ? null
              : props.form.getFieldValue('is_system') === IS_SYSTEM._FALSE
              ? 'ext_'
              : 'sys_'
          }
          disabled={props.actionType !== 'add'}
          style={compare(props, 'field_code')}
        />
      ),
    },

    {
      label: {
        label: '数据类型',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'data_type',
      options: {
        initialValue: data_type,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select
          style={{ width: '95%', ...compare(props, 'data_type') }}
          placeholder='请选择'
          disabled={props.actionType === 'detail'}
          onChange={handleTypeChange}
        >
          {props.data_types.map((it) => {
            return (
              <Select.Option value={it.code} key={it.code}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
      after: <DataTypeDesc dataType={props.form.getFieldValue('data_type')}></DataTypeDesc>,
    },
    {
      label: {
        label: '最大长度',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'max_length',
      options: {
        initialValue: max_length || 64,
        rules: [{ required: true, message: '请填写' }],
      },
      component: (
        <InputNumber
          max={9999999999}
          min={1}
          style={{ width: '100px', ...compare(props, 'max_length') }}
          disabled={props.form.getFieldValue('data_type') !== 'string' || props.actionType === 'detail'}
        />
      ),
    },
    {
      label: {
        label: '描述',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'remark',
      options: {
        initialValue: remark,
        rules: [{ max: 256, message: '最长256个字符' }],
      },
      component: (
        <Input
          placeholder='请填写简短描述,限256字内'
          style={compare(props, 'remark')}
          disabled={props.actionType === 'detail'}
        />
      ),
    },
    // {
    //   label: {
    //     label: '是否加密存储',
    //     className: 'tantuer-form-item3 tantuer-form-item-nowrap',
    //   },
    //   name: 'need_encrypt',
    //   options: {
    //     initialValue: need_encrypt || NEED_CALC._FALSE,
    //     rules: [{ required: true, message: '请选择' }],
    //   },
    //   component: (
    //     <Radio.Group disabled={props.actionType === 'detail'} className={compareClass(props, 'need_encrypt')}>
    //       <Radio value={NEED_CALC._TRUE}>是</Radio>
    //       <Radio value={NEED_CALC._FALSE}>否</Radio>
    //     </Radio.Group>
    //   ),
    // },
    props.form.getFieldValue('is_system') === IS_SYSTEM._FALSE
      ? // ? !props.isCompare
        {
          label: {
            label: '添加计算规则',
            className: 'tantuer-form-item3 tantuer-form-item-nowrap',
          },
          name: 'need_calc',
          options: {
            initialValue: need_calc || NEED_CALC._FALSE,
            rules: [{ required: true, message: '请选择' }],
          },
          component: (
            <Radio.Group disabled={props.actionType === 'detail'} className={compareClass(props, 'need_calc')}>
              <Radio value={NEED_CALC._TRUE}>是</Radio>
              <Radio value={NEED_CALC._FALSE}>否</Radio>
            </Radio.Group>
          ),
        }
      : false,
  ].filter(Boolean);

  const formItems3 = [
    {
      label: {
        label: '计算类型',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'calc_type',
      options: {
        initialValue: calc_type || CALC_TYPE._CONFIG,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Radio.Group disabled={props.actionType === 'detail'} className={compareClass(props, 'calc_type')}>
          <Radio.Button value={CALC_TYPE._CONFIG}>函数补全</Radio.Button>
          <Radio.Button value={CALC_TYPE._SQ}>自定义脚本</Radio.Button>
        </Radio.Group>
      ),
    },
  ];
  return (
    <div className='tantuer-form'>
      <Form onSubmit={() => false} className='login-form'>
        <div className='tantuer-field-area'>
          <Row type='flex'>
            {formItems.map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem {...props} form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
            <Col span={24} />
            {formItems2.map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem {...props} form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
            {props.form.getFieldValue('is_system') === IS_SYSTEM._FALSE &&
              props.form.getFieldValue('need_calc') === NEED_CALC._TRUE && (
                <>
                  <Col span={24}>
                    <Alert
                      message='说明：您可以通过以下两种方式定义字段的计算规则'
                      type='info'
                      style={{ marginBottom: '20px' }}
                    />
                  </Col>
                  {formItems3.map((item) => {
                    return (
                      <Col span={24} key={item.name}>
                        <FormItem {...props} form={props.form} item={item} colNum={1} />
                      </Col>
                    );
                  })}
                </>
              )}
          </Row>

          {props.form.getFieldValue('is_system') === IS_SYSTEM._FALSE &&
            props.form.getFieldValue('need_calc') === NEED_CALC._TRUE &&
            (props.form.getFieldValue('calc_type') === CALC_TYPE._CONFIG || !props.form.getFieldValue('calc_type')) && (
              <Row type='flex'>
                <Col span={6} style={{ width: '120px' }} />

                <Col span={18}>
                  <ActionSet
                    {...props}
                    variable={variable}
                    using_variables={using_variables}
                    onChange={handleChangeAction}
                    options={actionList}
                    value={calcContent}
                    compareData={props.compareData && props.compareData.calc_content}
                    disabled={props.actionType === 'detail'}
                    fieldId={props.record && props.record.field_id}
                  />
                </Col>
              </Row>
            )}
          {props.form.getFieldValue('is_system') === IS_SYSTEM._FALSE &&
            (props.form.getFieldValue('need_calc') === NEED_CALC._TRUE ||
              props.form.getFieldValue('need_calc') === '是') &&
            props.form.getFieldValue('calc_type') === CALC_TYPE._SQ && (
              <ScriptEditor
                onChange={handleScript}
                value={calcContentText}
                disabled={props.actionType === 'detail'}
                placeholder={`1.获取字段的值语法：field("字段code"); 例如获取code为a的字段值 field("a")\n2.特殊类型的字段类型转换\n例如code为a的字段值是字符串, 获取a的int值：Integer.valueOf(field("a"))\n3.表达式\n简单版：field("a") == null&&field("b") != null\n复杂版：Integer.valueOf(field("a")) == 0&&Double.valueOf(field("c"))>5`}
              />
            )}
        </div>
        {props.actionType === 'detail' ? (
          ''
        ) : (
          <div className='form-btn'>
            <Button type='primary' onClick={handleSubmit} className='login-form-button' autoFocus={true}>
              确定
            </Button>
            <Button className='login-form-button' onClick={() => props.closeModal && props.closeModal(true)}>
              取消
            </Button>
          </div>
        )}
      </Form>
    </div>
  );
}

function mapStateToProps(state) {
  return {
    field_classification: state.code.field_classification,
    data_types: state.code.data_type || []
  };
}
export default Form.create()(connect(mapStateToProps)(FieldAdd));
